<?php

namespace app\index\controller\session;

use app\index\service\SessionPhoneService;
use app\index\traits\SessionMemberDraftTrait;
use app\index\traits\SessionTrait;
use app\index\traits\TempTokenCheckTrait;
use ShidianUtil\Thinkphp\Response\ApiResponse;
use ShidianUtil\Utils\CheckUtil;
use think\exception\ValidateException;
use think\Request;

/**
 * 手机号验证码登录
 * 落地页登录
 * Class PhoneCaptcha
 * @package app\index\controller\session
 */
class PhoneCaptcha
{
    use SessionMemberDraftTrait;
    use TempTokenCheckTrait;
    use SessionTrait;

    private Request $request;

    private SessionPhoneService $service;

    public function __construct(Request $request, SessionPhoneService $thirdService)
    {
        $this->service = $thirdService;
        $this->request = $request;
    }

    /**
     * H5落地页-手机号验证码登录
     * @return ApiResponse
     * @url /session/phone_captcha/save
     */
    public function save(): ApiResponse
    {
        $request = $this->request;

        // 获取和验证登录信息（手机号，邀请码）
        $phone = $request->param('phone');
        $inviteCode = $request->param('inviteCode');

        // 渠道链路
        ['pf' => $pf, 'chain' => $chain, 'promotionGroupId' => $promotionGroupId] = getChainParams();

        if (is_blank($phone)) {
            throw new ValidateException('请输入手机号码');
        }
        if (!CheckUtil::isPhoneNumber($phone)) {
            throw new ValidateException('请输入正确的手机号码');
        }

        //先验证
        $this->checkMemberDraft($request->param('memberDraft'));

        // 验证短信验证码
        $this->checkCaptcha(CAPTCHA_DENGLU, $phone, $request->param('captcha'));

        $data['phone'] = $phone;
        $data['inviteCode'] = $inviteCode;
        $data['memberDraft'] = $request->param('memberDraft');

        $data['pf'] = $pf;
        $data['chain'] = $chain;
        $data['promotionGroupId'] = $promotionGroupId;

        // 登录
        return ApiResponse::success($this->service->login($data));
    }
}
